package com.zj.study.config;

import static org.springframework.core.ParameterizedTypeReference.forType;
import static org.springframework.web.servlet.function.RequestPredicates.GET;
import static org.springframework.web.servlet.function.RouterFunctions.route;
import static org.springframework.web.servlet.function.ServerResponse.ok;

import com.zj.study.autoconfig.WebAutoConfiguration;
import com.zj.study.config.properties.JwtConfigurationProperty;
import com.zj.study.entity.User;
import com.zj.study.pojo.FinalResultVO;
import com.zj.study.service.UserService;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @author 赵赳
 * @since 2021/10/25 17:15
 * @desc 此配置类不加@Configuration 因为使用了自动配置类 {@link WebAutoConfiguration}
 *                      所以不使用@Configuration注解也能将该类注入到IOC容器中
 */
@EnableConfigurationProperties(JwtConfigurationProperty.class)
public class WebConfiguration {

  private final UserService userService;
  public final static Map<String, List<User>> LOCAL = new ConcurrentHashMap<>();

  @Autowired
  public WebConfiguration(UserService userService) {
    this.userService = userService;
  }

  /**
   * 路由方式创建web
   *
   * @return 响应
   */
  @Bean
  public RouterFunction<ServerResponse> helloWorld() {
    return route(GET("/hello-world"),
        request -> ok().body(Mono.fromSupplier(() -> "hello-world"),
            forType(String.class))
    );
  }

  /**
   * 路由方式创建web
   *
   * @return 响应
   */
  @Bean
  public RouterFunction<ServerResponse> getUsers() {
    return route(GET("/users"),
        request -> ok()
            .body(Mono.fromSupplier(() -> FinalResultVO.ok(userService.lambdaQuery().list())),
                forType(FinalResultVO.class))
    );
  }

  /**
   * 监听springboot应用初始化
   *
   * @param event web容器初始化事件驱动
   */
  @EventListener(WebServerInitializedEvent.class)
  public void onWebServerReady(WebServerInitializedEvent event) {
    // web容器初始化后执行
    //var list = userService.list();
    //list.forEach(System.out::println);
    //LOCAL.put("user", list);
    System.out.println("当前webServer 实现类为：" + event.getWebServer().getClass().getName());
  }

}
